package LCR;

import java.util.ArrayList;
import java.util.List;

public class reorderList {
    public static void main(String[] args) {
        ListNode le = new ListNode();
        le.next = new ListNode(1);
        le.next.next = new ListNode(2);
        le.next.next.next = new ListNode(3);
        le.next.next.next.next = new ListNode(4);
        reorderList(le);
    }

    public static void reorderList(ListNode head) {
        if(head == null) {
            return;
        }
        ListNode mid = middleNode(head);
        ListNode l1 = head;
        ListNode l2 = mid.next;
        mid.next = null;
        l2 = reverseList(l2);
        mergeList(l1,l2);


    }
    public static void mergeList(ListNode l1, ListNode l2) {
        ListNode n1 ;
        ListNode n2 ;
        while(l1 != null && l2 != null) {
            n1 = l1.next;
            n2 = l2.next;

            l1.next = l2;
            l1 = n1;
            l2.next = l1;
            l2 = l2.next;
        }

    }
    public static ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode curN = head.next;
        head.next = null;
        while(curN != null) {
            cur = curN;
            curN = curN.next;
            cur.next = head;
            head = cur;
        }
        return cur;
    }
    public static ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }



    /*------------------------------------------------------------------*/
    public void reorderList1(ListNode head) {
        if(head == null) {
            return ;
        }
        List<ListNode> list  = new ArrayList<>();
        ListNode node = head;
        while(node != null) {
            list.add(node);
            node = node.next;
        }
        int i = 0,j = list.size() - 1;
        while(i < j) {
            list.get(i).next = list.get(j);
            i++;
            if(i == j) {
                break;
            }
            list.get(j).next = list.get(i);
            j--;
        }
        list.get(i).next = null;
    }
}
